package handler

import (
	"context"
	"errors"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"gorm.io/gorm"

	"mxshop_srvs/userop_srv/model"
	proto "mxshop_srvs/userop_srv/proto/gen/v1"
)

func FavoritesModelToPb(fav model.UserFav) *proto.UserFav {
	return &proto.UserFav{
		UserId:  fav.UserID,
		GoodsId: fav.GoodsID,
	}
}

func (s *Service) GetFavList(_ context.Context, req *proto.GetFavListRequest) (*proto.UserFavListResponse, error) {
	userFavorites, err := s.DB.GetUserFavorites(req.UserId)
	if err != nil {
		return nil, status.Error(codes.Internal, "")
	}

	favorites := make([]*proto.UserFav, 0, len(userFavorites))
	for _, fav := range userFavorites {
		favorites = append(favorites, FavoritesModelToPb(fav))
	}

	return &proto.UserFavListResponse{
		Total:     int32(len(favorites)),
		UserFaves: favorites,
	}, nil
}

func (s *Service) AddUserFav(_ context.Context, req *proto.UserFav) (*emptypb.Empty, error) {
	ID, err := s.DB.CreateUserFavorites(req.UserId, req.GoodsId)
	if err != nil {
		return nil, status.Error(codes.Internal, "")
	}
	if ID == 0 {
		return nil, status.Error(codes.InvalidArgument, "")
	}
	return &emptypb.Empty{}, nil
}

func (s *Service) DeleteUserFav(_ context.Context, req *proto.UserFav) (*emptypb.Empty, error) {
	row, err := s.DB.DeleteUserFavorite(req.UserId, req.GoodsId)
	if err != nil {
		return nil, status.Error(codes.Internal, "")
	}
	if row == 0 {
		return nil, status.Error(codes.NotFound, "收藏记录不存在")
	}
	return &emptypb.Empty{}, nil
}

func (s *Service) GetUserFavDetail(_ context.Context, req *proto.UserFav) (*emptypb.Empty, error) {
	_, err := s.DB.GetUserFavorite(req.UserId, req.GoodsId)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, status.Error(codes.NotFound, "收藏记录不存在")
		}
		return nil, status.Error(codes.Internal, "")
	}
	return &emptypb.Empty{}, nil
}
